<template>
  <Select
    v-model="currValue"
    :placeholder="placeholder"
    filterable
    clearable
    label-in-value
    :remote-method="remote"
    @on-query-change="onQueryChange"
    @on-change="onchange"
    @on-clear="remote"
    :loading="loading"
    @on-open-change="onOpen">
    <Option v-for="item in list" :key="item.id" :value="item.id">{{item.label}}</Option>
  </Select>
</template>
<script>
import { debounce } from '@/util'
export default {
  props: {
    placeholder: {
      type: String,
      default: '请输入活动名称'
    },
    value: {
      type: [String, Number],
      default: null
    },
    isLabelInvalue: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      name: '',
      oTimerDetail: null,
      reg: /^[0-9]+$/
    }
  },
  computed: {
    currValue: {
      get () {
        return this.value
      },
      set (v) {
        this.$emit('input', v || '')
      }
    }
  },
  mounted () {
    // this.getDetailData(this.name)
  },
  methods: {
    onchange (val) {
      if (val) {
        let target = this.list.find(item => item.id === val.value)
        this.$emit('onchange', target)
      }
    },
    onQueryChange(q) {
      if (!q) this.name = ''
    },
    onOpen (isOpen) {
      if (isOpen) {
        this.getDetailData()
      }
    },
    remote (query = '') {
      this.name = query
      this.getDetailData()
    },
    getDetailData: debounce(function d () {
      this.loading = true
      let isId = this.reg.test(this.name)
      let param = {
        activityStatus: 8,
      }
      if (isId) {
        param.activityId = this.name
        delete param.activityName
      } else {
        param.activityName = this.name
        delete param.activityId
      }
      return this.$ajaxGet('/activity/page', param).then(data => {
        this.loading = false
        this.list = (data.records || []).map(item => {
          return {
            id: item.id,
            label: item.activityName,
            tag: item.promotionTagName,
            tagId: item.promotionTagId
          }
        })
      }).catch(() => {
        this.loading = false
      })
    }, 300)
  }
}
</script>
